package com.sdcs.server.daoimpl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sdcs.server.model.Attendance;

@Component
public class AttendanceDaoImpl {
	@Autowired
	private SessionFactory sessionFactory;
	
	public void delete(String id) {
		Session sess = null;
		Transaction tx = null;
		
		try {
			sess = sessionFactory.openSession();
			tx = sess.beginTransaction();
			
			String hql = "delete Attendance where id = ?";
			sess.createQuery(hql).setParameter(0, Integer.parseInt(id)).executeUpdate();
			
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (sess != null) {
				sess.close();
			}
		}
	}
	
	public  void save(Attendance object){
		Session sess = null;
		Transaction tx = null;
		
		try {
			sess = sessionFactory.openSession();
			tx = sess.beginTransaction();
			
			sess.save(object);
			
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (sess != null) {
				sess.close();
			}
		}
	}
	
	public Attendance getObjectById(String id){
		Session sess = null;
		Transaction tx = null;
		
		try {
			sess = sessionFactory.openSession();
			tx = sess.beginTransaction();
			
			String hql = "from Attendance where id = ?";
			List<Attendance> list = sess.createQuery(hql, Attendance.class).setParameter(0, Integer.parseInt(id)).getResultList();
			
			if (!list.isEmpty()) {
				return list.get(0);
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (sess != null) {
				sess.close();
			}
		}
		return null;
	}
	
	public List<Attendance> getAll(){
		Session sess = null;
		Transaction tx = null;
		List<Attendance> list = new ArrayList<Attendance>();
		try {
			sess = sessionFactory.openSession();
			tx = sess.beginTransaction();
			
			String hql = "from Attendance order by id desc";
			list = sess.createQuery(hql, Attendance.class).getResultList();
			
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (sess != null) {
				sess.close();
			}
		}
		return list;
	}
}
